#include <Adafruit_NeoPixel.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#define PIN                         D6      // LED数据
#define LED_BRIGTHNESS              10      // LED亮度
#define NUMPIXELS                   60      // LED数量

char ssid_str[16] = "your-ssid";            // WIFI名称
char pass_str[16] = "your-pass";            // WIFI密码

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com", 60 * 60 * 8, 30 * 60 * 1000);
Adafruit_NeoPixel clk(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void ledShowAllColor(byte r, byte g, byte b)
{
  for (int i=0; i<NUMPIXELS; i++)
  {
       clk.setPixelColor(i, r, g, b);
  }
  clk.setBrightness (LED_BRIGTHNESS); 
  clk.show();
}

//LED圆形时钟显示初始化
void ledShowInit()
{
  clk.begin();
  clk.clear();                  // Set all pixel colors to 'off'
    
  ledShowAllColor(150, 150, 150);
}

//小时转成LED所位置
static byte getLEDHour(byte hours, byte minutes)
{
  if (hours > 12)
  {
    hours = hours - 12;
  }

  return hours*5;  
}

//分钟/秒钟转成LED所位置
static byte getLEDMinuteOrSecond(byte minuteOrSecond)
{
    return minuteOrSecond;
}


//LED圆形时钟刷新屏幕
void ledShowRefresh (byte hour_now, byte min_now, byte sec_now)
{
  //时分秒坐标位置转换
  byte hor_pos = getLEDHour(hour_now, min_now);
  byte min_pos = getLEDMinuteOrSecond(min_now);
  byte sec_pos = getLEDMinuteOrSecond(sec_now);
  
  clk.clear();
  clk.setPixelColor(hor_pos, clk.Color(150, 0, 0));
  clk.setPixelColor(min_pos, clk.Color(0, 150, 0));
  clk.setPixelColor(sec_pos, clk.Color(0, 0, 150));

  Serial.printf("Pos %02d:%02d:%02d\r\n", hor_pos, min_pos, sec_pos);  
  clk.setBrightness (LED_BRIGTHNESS); 
  clk.show();
}


void setup()
{
  //串口初数化
  Serial.begin(115200);
  Serial.println("\r\nSystem Init!");
  
  //LED显示初始化
  ledShowInit();
  delay(1000);

  Serial.printf("SSID:%s\r\n", ssid_str);
  Serial.printf("PSWD:%s\r\n", pass_str);

  //WIFI连接
  ledShowAllColor(150, 0, 0);
  WiFi.begin(ssid_str, pass_str);
  while ( WiFi.status() != WL_CONNECTED )
  {
    delay(1000);
    Serial.print (".");
  }
  Serial.println(" ");

  ledShowAllColor(0, 150, 0);
  delay(1000);

  //NTP服务初始化
  timeClient.begin();
  delay(10);
}

void loop()
{
  //NTP获取时间
  timeClient.update();
  int hours   = timeClient.getHours();
  int minutes = timeClient.getMinutes();
  int seconds = timeClient.getSeconds();
  Serial.printf("Time %02d:%02d:%02d  ", hours, minutes, seconds);

  //LED刷新时间
  ledShowRefresh(hours, minutes, seconds);
  delay(1000);
}